package tw.twandroidproj.app.network;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.koushikdutta.async.future.Future;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.Response;
import com.orm.SugarRecord;

import java.lang.reflect.Type;
import java.sql.SQLInvalidAuthorizationSpecException;
import java.util.List;
import java.util.Map;

import tw.twandroidproj.app.model.Auth;
import tw.twandroidproj.app.model.ErrorModel;
import tw.twandroidproj.app.model.Resume;
import tw.twandroidproj.app.model.User;

/**
 * Created by Frezc on 2015/11/5.
 * 用来管理用户登录的工具类
 */
public class AuthManager {

    private Context context;
    private Future<?> authFuture;
    private Object futureGroup = new Object();

    /***
     * 进行登录验证的函数
     * @param email
     * @param password
     * @param callback
     * @return
     */
    public Future<?> auth(String email, String password, final OnResponseListener<Auth> callback){
        authFuture = Ion.with(context)
                .load(NetParams.AUTH_URL)
                .setBodyParameter("email", email)
                .setBodyParameter("password", password)
                .asString()
                .withResponse()
                .setCallback(new FutureCallback<Response<String>>() {
                    @Override
                    public void onCompleted(Exception e, Response<String> result) {
                        Gson gson = new Gson();
                        if (result.getHeaders().code() == 200){
                            Auth auth = gson.fromJson(result.getResult(), Auth.class);
                            //todo: 保存用户信息到数据库
                            SugarRecord.save(auth.getUser());
                            SugarRecord.save(auth);
                            Log.i("SmiLe", "save success");
                            callback.onSuccess(auth);
                        } else if (result.getHeaders().code() == 401){
                            callback.onFailed(gson.fromJson(result.getResult(), ErrorModel.class));
                        }

                        authFuture = null;
                    }
                });
        return authFuture;
    }
    /***
     * 一个通用的get请求方法
     * @param url 请求地址
     * @param listener 回调接口
     * @param type 泛型的Type对象, 如果是普通类 type =  (Type) MyClass.class; 带泛型(如数组) type = new TypeToken<List<MyClass>>(){}.getType();
     * @param <T> 请求得到的对象类型
     * @return
     */
    public <T> Future<?> get (String url, final OnResponseListener<T> listener, final Type type) {
        return Ion.with(context)
                .load(url)
                .group(futureGroup)
                .asString()
                .withResponse()
                .setCallback(new FutureCallback<Response<String>>() {
                    @Override
                    public void onCompleted(Exception e, Response<String> result) {
                        Gson gson = new Gson();
                        if (result.getHeaders().code() == 200) {
                            //todo
                            T t = gson.fromJson(result.getResult(), type);
                            listener.onSuccess(t);
                        } else {
                            listener.onFailed(gson.fromJson(result.getResult(), ErrorModel.class));
                        }
                    }
                });
    }

    /***
     * 如果返回不是数组时建议调用该函数
     * @param url 请求地址
     * @param listener 回调接口
     * @param clazz 对象对应的Class类 clazz = MyClass.class;
     * @param <T> 请求得到的对象类型
     * @return
     */
    public <T> Future<?> get (String url, OnResponseListener<T> listener, Class<T> clazz) {
        return this.get(url, listener, (Type) clazz);
    }

    /**
     * 电话登录
     * @param url

     */
    public void authPhone (String url, Map<String, String> map, OnResponseListener<String> listener){

    }

    /***
     * 是否登录
     */
    public boolean isLogined() {
        //todo: 根据数据库保存的token
        List<User> list_found=SugarRecord.listAll(User.class);
        Log.i("SmiLe",String.valueOf(list_found));
        if (list_found.size()!=0)
            return true;
        return false;
    }

    /***
     * 返回验证的token
     */
    public String getToken() {
        //todo
        List<Auth> list=SugarRecord.listAll(Auth.class);
        return list.get(0).getToken();
    }
    /**
     * 刷新token
     * @param token 旧token，刷新后就不再使用了
     */
    public Future<Response<String>> refresh (String token, final OnResponseListener<String> listener){
        return Ion.with(context)
                .load(NetParams.REFRESH + "?token=" + token)
                .group(futureGroup)
                .asString()
                .withResponse()
                .setCallback(new FutureCallback<Response<String>>() {
                    @Override
                    public void onCompleted(Exception e, Response<String> result) {
                        if(result==null){
                                ErrorModel errorModel_netfail=new ErrorModel();
                                errorModel_netfail.setStatus_code(-1);
                                listener.onFailed(errorModel_netfail);
                        }
                        else if (result.getHeaders().code() == 200) {
                            //todo
                            Gson gson = new Gson();

                                Auth auth = gson.fromJson(result.getResult(), Auth.class);
                                //todo: 保存用户信息到数据库
//                            String str=result.getHeaders().getHeaders().get("Authorization");
                            List<Auth> list=SugarRecord.listAll(Auth.class);
                            Auth auth_refresh=list.get(0);
                            auth_refresh.setToken(auth.getToken());
                            Log.i("token",auth.getToken());
                            SugarRecord.save(auth_refresh);
                            SugarRecord.save(auth_refresh.getUser());
                            Log.i("tokensave","success");
                            listener.onSuccess("");
                        } else if(result.getHeaders().code() == 0){
                            Log.i("##@#@#token_r","fail");
                            ErrorModel errorModel_tokenfail=new ErrorModel();
                            errorModel_tokenfail.setStatus_code(0);
                            listener.onFailed(errorModel_tokenfail);
                        }
                    }
                });
    }


    /***
     * 是否正在登录
     */
    public boolean isLogining() {
        return authFuture != null;
    }

    /***
     * 取消登录
     */
    public void cancel() {
        if (isLogining()){
            authFuture.cancel();
        }
    }

    /***
     * 得到已登录的用户信息
     * @return
     */
    public User getLoginUser() {
        if (isLogined()) {
            //todo
            List<User> list_found=SugarRecord.listAll(User.class);
            return list_found.get(0);
        } else {
            return null;
        }
    }

    /***
     * 退出登录
     * 执行一些清理工作
     */
    public void logout() {
        SugarRecord.deleteAll(User.class);
        SugarRecord.deleteAll(Auth.class);
    }

    //单例类 usage: AuthManager manager = AuthManager.getInstance(this);
    //////////////////////////////////////////////////////
    private volatile static AuthManager instance;

    private AuthManager(Context context) {
        this.context = context.getApplicationContext();
    }

    public static AuthManager getInstance(Context context) {
        if (instance == null){
            synchronized (AuthManager.class) {
                if (instance == null){
                    instance = new AuthManager(context);
                }
            }
        }
        return instance;
    }
    ///////////////////////////////////////////////////////

}
